﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PaliTextReader2.Utilities;
using System.Drawing.Text;

namespace PaliTextReader2
{
    public partial class SelectBook : Form
    {
        bool bFirstLoad = true;
        int m_nFileID;
        int m_nNodeID;
        string m_strPTSPage;
        int m_nScrollPos=-1;

        public int ScrollPos
        {
            get { return m_nScrollPos; }
            set { m_nScrollPos = value; }
        }

        public int FileID
        {
            get { return m_nFileID; }
            set { m_nFileID = value; }
        }

        public int NodeID
        {
            get { return m_nNodeID; }
            set { m_nNodeID = value; }
        }

        public string PTSPage
        {
            get { return m_strPTSPage; }
            set { m_strPTSPage = value; }
        }

        /// <summary>
        /// invoked with Select Book command
        /// </summary>
        public SelectBook()
        {
            InitializeComponent();
        }

        /// <summary>
        /// invoked with quickNav
        /// </summary>
        /// <param name="FileID"></param>
        public SelectBook(int FileID)
        {//quickNav
            InitializeComponent();
            m_nFileID = FileID;
        }

        private void SelectBook_Load(object sender, EventArgs e)
        {
            if (bFirstLoad)
            {
                if (m_nFileID > 0)
                {//quickNav
                    Text = "Quick navigation";

                    ctlTabControl.TabPages.Remove(tabPage2);
                    ctlTabControl.TabPages.Remove(tabPage5);

                    //contents tab
                    ContentsDS.NodesDataTable objNodesTable = m_objNodesTA.GetFileName(m_nFileID);
                    TreeNode objRootNode = ctlTreeContents.Nodes.Add(objNodesTable[0].NodeID.ToString(), objNodesTable[0].NodeTitle);
                    TreeNode objChildNode = objRootNode.Nodes.Add("-1", "",0);
                    objRootNode.Expand();

                    //PTS Page tab
                    ContentsDS.FilesDataTable objFiles=m_objFilesTA.GetByFileID(m_nFileID);
                    if (objFiles[0].IsCollectionIDNull())
                    {
                        ctlTabControl.TabPages.Remove(tabPage3);
                    }
                    else
                    {
                        ctlPTSBook.Visible = false;
                        ctlPTSBookLabel.Visible = false;

                        ContentsDS.PTSPagesAggDataTable objPages = m_objPTSPagesAggTA.FindByFile(m_nFileID);
                        if (objPages == null || objPages.Rows.Count == 0)
                        {
                            ctlVolume.Items.Clear();
                            ctlVolume.Enabled = false;
                            ctlPage.Enabled = false;
                        }
                        else
                        {
                            ctlVolume.Enabled = true;
                            ctlPage.Enabled = true;

                            ctlVolume.DataSource = objPages;

                            if (ctlVolume.Items.Count == 1)
                            {
                                ctlVolume.SelectedIndex = 0;
                                ctlVolume.Enabled = false;
                            }
                        }
                    }

                    //bookmarks
                    tabPage4.Text = "Bookmarks in this book";


                    //if (objFiles[0].FileName.IndexOf("mul") > 0)
                    //{
                    //    ctlAtthakatha.Visible = true;
                    //    ctlTika.Visible = true;
                    //}
                }
                else
                {//select book
                    ContentsDS.NodesDataTable objRootNodes = m_objNodesTA.GetRootNodes();
                    foreach (ContentsDS.NodesRow objRow in objRootNodes)
                    {
                        TreeNode objRootNode = ctlTreeContents.Nodes.Add(objRow.NodeID.ToString(), objRow.NodeTitle);
                        objRootNode.Nodes.Add("-1", "",1,1);
                    }

                    ctlSearchMode.SelectedIndex = 0;

                    ContentsDS.CollectionsDataTable objRootItems = m_objCollectionsTA.GetRootItems(true);
                    foreach (ContentsDS.CollectionsRow objRow in objRootItems)
                    {
                        ctlPTSBook.Items.Add(objRow);
                        ContentsDS.CollectionsDataTable objChildItems = m_objCollectionsTA.GetChildItems(objRow.CollectionID,true);
                        foreach (ContentsDS.CollectionsRow objChildRow in objChildItems)
                        {
                            objChildRow.Title = "  " + objChildRow.Title;
                            ctlPTSBook.Items.Add(objChildRow);
                        }
                    }
                }

                bFirstLoad = false;
            }

            if (m_nFileID > 0)
            {
                List<BookmarkInfo> arrBookBookmarks = new List<BookmarkInfo>();
                foreach (BookmarkInfo objBookmark in AppState.Instance().Bookmarks)
                    if (objBookmark.FileID == m_nFileID)
                        arrBookBookmarks.Add(objBookmark);

                BindingList<BookmarkInfo> objBookBL = new BindingList<BookmarkInfo>(arrBookBookmarks);
                ctlBookmarks.DataSource = objBookBL; 
            }
            else
            {
                BindingList<BookmarkInfo> objBL = new BindingList<BookmarkInfo>(AppState.Instance().Bookmarks);
                ctlBookmarks.DataSource = objBL;

                BindingList<BookmarkInfo> objRecentBooks = new BindingList<BookmarkInfo>(AppState.Instance().RecentBooks);
                ctlRecentBooks.DataSource = objRecentBooks;
            }
        }

        private void ctlTreeContents_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Nodes.Count > 0 && e.Node.Nodes[0].Name == "-1")
            {
                e.Node.Nodes.RemoveAt(0);

                ContentsDS.NodesDataTable objNodes = m_objNodesTA.GetNodesByParent(
                    Int32.Parse(e.Node.Name));

                foreach (ContentsDS.NodesRow objRow in objNodes)
                {
                    int ImageIndex=objRow.IsFileIDNull() ? 0 : 
                        objRow.IsBookmarkNameNull() ? 1 : 2;
                    TreeNode objChildNode = e.Node.Nodes.Add(objRow.NodeID.ToString(),
                        objRow.NodeTitle, ImageIndex, ImageIndex);

                    objChildNode.Tag = objRow;

                    if (objRow.HasChildren)
                        objChildNode.Nodes.Add("-1", "");                        
                }
            }
        }

        private void ctlFind_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ctlSearchBox.Text))
            {
                ContentsDS.NodesDataTable dtResults = null;

                if (ctlIgnoreDiac.Checked)
                    dtResults = m_objNodesTA.FindNodesNoDiac(ctlSearchMode.SelectedIndex, Utility.ConvertDiac(ctlSearchBox.Text));
                else
                    dtResults = m_objNodesTA.FindNodesPali(ctlSearchMode.SelectedIndex, ctlSearchBox.Text);
                
                ctlFoundItems.DataSource = dtResults;
            }
        }

        private void ctlFoundItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            ctlLocation.Text = String.Empty;
            ctlLocation.Text = Utility.GetNodePath(Convert.ToInt32(ctlFoundItems.SelectedValue));
        }

        private void ctlPTSBook_SelectedIndexChanged(object sender, EventArgs e)
        {
            ContentsDS.CollectionsRow objRow = (ContentsDS.CollectionsRow)ctlPTSBook.SelectedItem;
            ContentsDS.PTSPagesAggDataTable objPages=m_objPTSPagesAggTA.GetData(objRow.CollectionID);
            if (objPages == null || objPages.Rows.Count == 0)
            {
                ctlVolume.Items.Clear();
                ctlVolume.Enabled = false;
                ctlPage.Enabled = false;
            }
            else
            {
                ctlVolume.Enabled = true;
                ctlPage.Enabled = true;

                ctlVolume.DataSource = objPages;

                if (ctlVolume.Items.Count == 1)
                {
                    ctlVolume.SelectedIndex = 0;
                    ctlVolume.Enabled = false;
                }
            }
        }

        private void ctlVolume_SelectedIndexChanged(object sender, EventArgs e)
        {
            ContentsDS.PTSPagesAggRow objRow = (ContentsDS.PTSPagesAggRow)((DataRowView)ctlVolume.SelectedItem).Row;
            ctlPage.Minimum = objRow.MinPage;
            ctlPage.Maximum = objRow.MaxPage;            
            ctlPage.Value = ctlPage.Minimum;
        }

        private void ctlOK_Click(object sender, EventArgs e)
        {
            bool bSuccess = false;

            if (ctlTabControl.SelectedTab == tabPage1)
            {
                if (ctlTreeContents.SelectedNode == null)
                    MessageBox.Show("Select a node to open");
                else
                {
                    if (ctlTreeContents.SelectedNode.Tag == null)
                        MessageBox.Show("You cannot open a Pitaka or Nikaya.");
                    else
                    {
                        ContentsDS.NodesRow objRow = (ContentsDS.NodesRow)ctlTreeContents.SelectedNode.Tag;
                        if(objRow.IsFileIDNull())
                            MessageBox.Show("You cannot open a Pitaka or Nikaya.");
                        else
                        {
                            m_nNodeID = objRow.NodeID;
                            m_nFileID = -1;
                            m_strPTSPage = String.Empty;
                            bSuccess = true;
                        }
                    }
                }
            }

            if (ctlTabControl.SelectedTab == tabPage2)
            {
                if (ctlFoundItems.SelectedIndex > -1)
                {
                    ContentsDS.NodesRow objSelectedNode = (ContentsDS.NodesRow)((DataRowView)ctlFoundItems.SelectedItem).Row;
                    if (objSelectedNode.IsFileIDNull())
                        MessageBox.Show("You cannot open a Pitaka or Nikaya.");
                    else
                    {
                        m_nNodeID = objSelectedNode.NodeID;
                        m_nFileID = -1;
                        m_strPTSPage = String.Empty;
                        bSuccess = true;
                    }
                }
                else
                    MessageBox.Show("You must select a book in the list.");
            }

            if (ctlTabControl.SelectedTab == tabPage3)
            {
                if (ctlPage.Enabled == false)
                    MessageBox.Show("You must specify volume and page number to proceed");
                else
                {
                    ContentsDS.PTSPagesAggRow objVolumeRow = (ContentsDS.PTSPagesAggRow)((DataRowView)ctlVolume.SelectedItem).Row;
                    if (m_nFileID<1)
                    {
                        ContentsDS.CollectionsRow objBookRow = (ContentsDS.CollectionsRow)ctlPTSBook.SelectedItem;
                        m_nFileID = m_objPTSPagesTA.FindFileByPage(objVolumeRow.VolumeID,
                            (int)ctlPage.Value, (int?)objBookRow.CollectionID) ?? 0;
                    }

                    m_strPTSPage = String.Format("{0}.{1:0000}", objVolumeRow.VolumeID,ctlPage.Value);
                    m_nNodeID = -1;
                    bSuccess = true;
                }
            }

            if (ctlTabControl.SelectedTab == tabPage4)
            {
                if (ctlBookmarks.SelectedItem == null)
                    MessageBox.Show("You must select a bookmark");
                else
                {
                    BookmarkInfo objBookmark = (BookmarkInfo)ctlBookmarks.SelectedItem;
                    m_nFileID = objBookmark.FileID;
                    m_nScrollPos = objBookmark.ScrollPos;
                    bSuccess = true;
                }
            }

            if (ctlTabControl.SelectedTab == tabPage5)
            {
                if (ctlRecentBooks.SelectedItem == null)
                    MessageBox.Show("You must select a book");
                else
                {
                    BookmarkInfo objBookmark = (BookmarkInfo)ctlRecentBooks.SelectedItem;
                    m_nFileID = objBookmark.FileID;
                    m_nScrollPos = objBookmark.ScrollPos;
                    bSuccess = true;
                }
            }

            if (bSuccess)
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        private void ctlEdit_Click(object sender, EventArgs e)
        {
            if (ctlBookmarks.SelectedItem != null)
            {
                BookmarkInfo objBookmark = (BookmarkInfo)ctlBookmarks.SelectedItem;
                BookmarkNameDlg dlgBookmarkName = new BookmarkNameDlg();
                dlgBookmarkName.BookmarkName = objBookmark.BookmarkName;
                if (dlgBookmarkName.ShowDialog() == DialogResult.OK)
                {
                    objBookmark.BookmarkName = dlgBookmarkName.BookmarkName;
                    ((BindingList<BookmarkInfo>)ctlBookmarks.DataSource).ResetItem(ctlBookmarks.SelectedIndex);
                }
            }
        }

        private void ctlDelete_Click(object sender, EventArgs e)
        {
            if (ctlBookmarks.SelectedItem != null)
                if (MessageBox.Show("Are you sure?","Confirm",MessageBoxButtons.YesNo) == DialogResult.OK)
                {
                    BookmarkInfo objBookmark = (BookmarkInfo)ctlBookmarks.SelectedItem;
                    AppState.Instance().Bookmarks.Remove(objBookmark);
                }
        }

        private void ctlSearchBox_KeyDown(object sender, KeyEventArgs e)
        {
            PaliKeyboard.HandlePaliKeys(ctlSearchBox, e);

            if (e.KeyCode == Keys.Enter)
                ctlFind_Click(null,null);
        }

        #region this doesn't work. another approach is nessessary
        private void ctlAtthakatha_Click(object sender, EventArgs e)
        {
            FindCommentary("a.att");
        }

        private void ctlTika_Click(object sender, EventArgs e)
        {
            FindCommentary("t.tik");
        }

        private void FindCommentary(string strCommKey)
        {
            if (ctlTreeContents.SelectedNode.Tag != null)
            {
                ContentsDS.NodesRow objNodeRow = (ContentsDS.NodesRow)ctlTreeContents.SelectedNode.Tag;
                ContentsDS.FilesDataTable objFiles = m_objFilesTA.GetByFileID(m_nFileID);
                //this will not work for multi file books of AN and SN :-(
                string strFileName = objFiles[0].FileName.Replace("m.mul", strCommKey);
                ContentsDS.FilesDataTable objAttFiles = m_objFilesTA.GetByName(strFileName);
                if (objAttFiles.Rows.Count > 0)
                {
                    ContentsDS.NodesDataTable objNodes = m_objNodesTA.GetByFileBookmark(objAttFiles[0].FileID, objNodeRow.BookmarkName);
                    if (objNodes.Rows.Count > 0)
                    {
                        m_nNodeID = objNodes[0].NodeID;
                        m_nFileID = objAttFiles[0].FileID;
                        m_strPTSPage = String.Empty;
                        m_nScrollPos = -1;
                        DialogResult = DialogResult.OK;
                        Close();
                    }
                }
            }
        }

        #endregion

        private void ctlFoundItems_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            e.DrawFocusRectangle();
            Rectangle bounds = e.Bounds;
            Size imageSize = ctlNodeImages.ImageSize;

            ContentsDS.NodesRow objRow = (ContentsDS.NodesRow)((DataRowView)ctlFoundItems.Items[e.Index]).Row;
            int ImageIndex=objRow.IsFileIDNull() ? 0 : objRow.IsBookmarkNameNull() ? 1 : 2;
            Bitmap objBitmap = new Bitmap(ctlNodeImages.Images[ImageIndex]);
            objBitmap.MakeTransparent(Color.White);
            e.Graphics.DrawImage(objBitmap, new Point(bounds.Left, bounds.Top));

            //this honors ClearType unlike e.Graphics.DrawString
            TextRenderer.DrawText(e.Graphics, objRow.NodeTitle, e.Font, 
                new Point(bounds.X + imageSize.Width,bounds.Top),
                e.ForeColor,e.BackColor);
        }

        private void ctlRecentBooks_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            e.DrawFocusRectangle();
            Rectangle bounds = e.Bounds;
            Size imageSize = ctlNodeImages.ImageSize;

            BookmarkInfo objBI = ctlRecentBooks.Items[e.Index] as BookmarkInfo;
            
            Bitmap objBitmap = new Bitmap(ctlNodeImages.Images[1]);
            objBitmap.MakeTransparent(Color.White);
            e.Graphics.DrawImage(objBitmap, new Point(bounds.Left, bounds.Top));

            //this honors ClearType unlike e.Graphics.DrawString
            TextRenderer.DrawText(e.Graphics, objBI.BookmarkName, e.Font,
                new Point(bounds.X + imageSize.Width, bounds.Top),
                e.ForeColor, e.BackColor);
        }

        private void ctlBookmarks_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            e.DrawFocusRectangle();
            Rectangle bounds = e.Bounds;
            Size imageSize = ctlNodeImages.ImageSize;

            if (ctlRecentBooks.Items.Count > 0)
            {
                BookmarkInfo objBI = ctlRecentBooks.Items[e.Index] as BookmarkInfo;

                Bitmap objBitmap = new Bitmap(ctlNodeImages.Images[3]);
                objBitmap.MakeTransparent(Color.White);
                e.Graphics.DrawImage(objBitmap, new Point(bounds.Left, bounds.Top));

                //this honors ClearType unlike e.Graphics.DrawString
                TextRenderer.DrawText(e.Graphics, objBI.BookmarkName, e.Font,
                    new Point(bounds.X + imageSize.Width, bounds.Top),
                    e.ForeColor, e.BackColor);
            }
        }
    }
}
